import { Injectable } from '@angular/core';

@Injectable()
export class ArrayTreeService {

    convertTreeToArray (data, c) {
        if (!Array.isArray(data)) {
            throw new TypeError('array-unique expects an array.');
        }
        let config = {
            needDelete: c.needDelete ? c.needDelete : false,
            children: c.children ? c.children : 'children'
        };

        let array = [];

        function convert(data) {
            let n = Object.assign({}, data);
            config.needDelete && delete n[config.children];
            array.push(n);

            if (data[config.children]) {
                for (let c of data[config.children]) {
                    convert(c);
                }
            }
        }
        for (let d of data) {
            convert(d);
        }

        return array;
    }

    convertArrayToTree (data, c) {
        let cloneData = JSON.parse(JSON.stringify(data));
        let tree = cloneData.filter(father => {
            let branchArr = cloneData.filter(child => {
                return father[c.key] === child[c.parentKey];
            });
            if (branchArr.length > 0) {
                father[c.children] = branchArr;
            }
            return father[c.parentKey] === c.topRootValue;
        });
        return tree;
    }
}
